<template>
  <div
    class="bookmarks-box"
    v-loading="loading"
    element-loading-background="rgba(122, 122, 122, 0.8)"
  >
    <div class="head-operation-box">
      <el-input
        v-model="keywords"
        style="width: 340px"
        placeholder="请输入关键字进行搜索"
        prefix-icon="Search"
        @keyup.enter="getBookMarksList"
      />
      <div v-if="!planet">
        <el-button type="primary" @click="addBookMark">添加</el-button>
      </div>
    </div>
    <div class="" v-if="total != 0">
      <div class="toolbar" v-if="!planet && selectData.length > 0">
        <el-checkbox
          v-model="checkAll"
          @change="selectAllBookmarks"
          :indeterminate="isIndeterminate"
          >全选</el-checkbox
        >
        <el-button icon="Star" @click="setAsterisks(1)">设置星标</el-button>
        <el-button icon="Star" @click="setAsterisks(0)">取消星标</el-button>
        <el-button type="danger" icon="Delete" @click="delBookMark()"
          >批量删除</el-button
        >
      </div>
      <div class="list-content">
        <div
          v-for="(item, index) in bookmarksList"
          :key="index"
          class="card-box"
        >
          <el-checkbox
            v-if="!planet"
            class="h-checkbox"
            v-model="item.isChecked"
            @change="selectBookmark"
          ></el-checkbox>
          <el-dropdown trigger="click" placement="right">
            <el-card style="width: 245px" shadow="hover">
              <template #header>
                <div style="height: 170px">
                  <img
                    v-if="!item.favIconUrl"
                    src="../assets/images/TrPUZn.png"
                    style="width: 100%; height: 100%"
                  />
                  <img
                    v-else
                    :src="item.favIconUrl"
                    style="width: 100%; height: 100%"
                  />
                </div>
              </template>
              <div class="card-body">
                <h1>{{ item.title }}</h1>
                <p>{{ item.description }}</p>
                <div class="b-f">
                  <img src="../assets/images/icon-16.png" />
                  <span>{{
                    item.url.match(
                      /^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:/\n?]+)/i
                    )[1]
                  }}</span>
                  <span style="font-size: 12px">{{
                    item.createdAt.split(" ")[0]
                  }}</span>
                  <span v-if="item.asterisk == 1 && !planet"
                    ><el-icon><Star /></el-icon
                  ></span>
                </div>
              </div>
            </el-card>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item icon="Link" @click="openPage(item.url)"
                  >打开链接</el-dropdown-item
                >
                <el-dropdown-item icon="View" @click="viewPage(item)"
                  >阅读模式</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="!planet"
                  icon="Edit"
                  @click="editBookMark(item.id)"
                  >编辑信息</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="!planet"
                  icon="Star"
                  @click="setAsterisk(item)"
                  >{{
                    item.asterisk == 1 ? "取消" : "设置"
                  }}星标</el-dropdown-item
                >
                <el-dropdown-item
                  v-if="!planet"
                  icon="Delete"
                  @click="delBookMark(item.id)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </div>
    <data-empty v-else></data-empty>
    <div class="paginator-content">
      <el-pagination
        style="justify-content: center"
        :hide-on-single-page="true"
        :page-size="pageSize"
        :page-count="maxPage ? maxPage : 1"
        :pager-count="7"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
  </div>

  <el-dialog
    v-model="dialog.visible"
    :title="isEdit ? '编辑书签' : '新增书签'"
    width="486px"
    destroy-on-close
    @close="resetForm"
  >
    <cloud-form
      ref="formRef"
      v-model="formData"
      :formConfig="formConfig"
    ></cloud-form>
    <template #footer>
      <el-button @click="dialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submit(formRef)">确定</el-button>
    </template>
  </el-dialog>
  <div class="iframe" v-if="dialog.isView">
    <span class="close" @click="dialog.isView = false"
      ><el-icon><Close /></el-icon
    ></span>
    <h1 class="title">阅读模式</h1>
    <iframe
      :src="bookmarkDetail.url"
      frameborder="0"
      style="width: 100%; height: 800px"
    ></iframe>
    <div class="tool">
      <div>收藏用户：{{ bookmarkDetail.username }}</div>
      <ul>
        <li title="点赞" @click="handleLikeClick">
          <img v-if="!likeStatus" src="../assets/images/like.png" />
          <img v-else src="../assets/images/tobarThumbUpactive.png" />
          &nbsp;{{ likeCount }}
        </li>
        <li title="评论" @click="dialog.drawer = true">
          <img src="../assets/images/comment.png" />&nbsp;{{
            comments.length || ""
          }}
        </li>
        <li title="分享"><img src="../assets/images/share.png" />&nbsp;分享</li>
      </ul>
    </div>
  </div>
  <el-drawer v-model="dialog.drawer" title="评论" direction="rtl">
    <div class="drawer__content" v-if="comments.length > 0">
      <div
        class="comment_box"
        v-for="(item, index) in comments"
        :key="index"
        @mouseenter="item.showDel = true"
        @mouseleave="item.showDel = false"
      >
        <div class="head">
          <span class="avter"
            ><el-icon><UserFilled /></el-icon
          ></span>
          <span class="username">{{ item.username }}</span>
          <span class="time">{{ item.createdAt }}</span>
          <span
            class="icon"
            v-if="item.userId == userId"
            v-show="item.showDel"
            @click="delComment(item)"
            ><el-icon><Delete /></el-icon
          ></span>
        </div>
        <div class="body">{{ item.content }}</div>
      </div>
    </div>
    <div class="empty" v-else>
      <el-empty description="暂无评论" />
    </div>
    <div class="drawer__footer">
      <el-input
        v-model="commentContent"
        placeholder="请输入评论内容"
        type="textarea"
        rows="6"
      ></el-input>
      <div class="foot_btn">
        <el-button type="primary" @click="commentSubmit()">发表评论</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { mAxios, encodeURL } from "~/utils/axios/axios.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useBookMarkStore } from "~/utils/pinia/bookmark.js";
import moment from "moment";
import { useRouter } from "vue-router";
let $router = useRouter();
const bookMarkStore = useBookMarkStore();
const planet = ref(false);
if ($router.currentRoute.value.path == "/planet") {
  planet.value = true;
}
const props = defineProps({
  // 请求额外参数
  query: {
    type: Object,
    default: {},
  },
});
// 从外部传入的list接口请求参数
const apiParams = defineModel();

const loading = ref(false);
const isEdit = ref(false);
const userId = Number(sessionStorage.getItem("user_id"));
const dialog = reactive({
  visible: false,
  isView: false,
  drawer: false,
});
const formRef = ref();
const formData = ref({});
const formConfig = ref([]);
const fields = [
  {
    label: "标题",
    prop: "title",
    type: "input",
    required: true,
    setting: {
      placeholder: "请输入书签标题",
    },
  },
  {
    label: "链接地址",
    prop: "url",
    type: "input",
    required: true,
    setting: {
      placeholder: "请输入链接地址",
    },
  },
  {
    label: "描述",
    prop: "description",
    type: "input",
    setting: {
      placeholder: "请输入描述",
    },
  },
  {
    label: "分组",
    prop: "groupId",
    type: "select",
    setting: {
      placeholder: "请选择分组",
      remote: true,
      remoteMethod: (form) => {
        return new Promise((resolve, reject) => {
          mAxios.get(`group/list/${userId}`).then((res) => {
            let s = res.data.data?.map((item) => {
              return {
                label: item.groupName,
                value: item.id,
              };
            });
            resolve([{ label: "我的目录", value: 0 }].concat(s));
          });
        });
      },
    },
  },
  {
    label: "标签",
    prop: "tags",
    type: "select",
    setting: {
      placeholder: "请选择标签",
      multiple: true,
      collapseTags: true,
      collapseTagsTooltip: true,
      remote: true,
      remoteMethod: (form) => {
        return new Promise((resolve, reject) => {
          mAxios.get(`tags`, { params: encodeURL({ userId }) }).then((res) => {
            let s = res.data.data?.map((item) => {
              return {
                label: item.tagName,
                value: item.id,
              };
            });
            resolve(s);
          });
        });
      },
    },
  },
  {
    label: "是否星标",
    prop: "asterisk",
    type: "checkbox",
    setting: {
      trueValue: 1,
      falseValue: 0,
    },
  },
];
const submit = (formRef) => {
  if (!formRef) return;
  formRef.validate((valid) => {
    if (valid) {
      let req;
      const params = { ...formData.value, userId };
      if (isEdit.value) {
        req = mAxios.put("bookmarks", params);
      } else {
        req = mAxios.post("bookmarks", params);
      }
      req.then((res) => {
        dialog.visible = false;
        res.data.succeed
          ? ElMessage.success("操作成功")
          : ElMessage.error("操作失败");
        getBookMarksList();
      });
    }
  });
};

const keywords = ref(null);
const bookmarksList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const maxPage = computed(() => {
  return total.value > 10000
    ? Math.ceil(10000 / pageSize.value)
    : Math.ceil(total.value / pageSize.value);
});
const getBookMarksList = () => {
  if (apiParams.value.type == "new") {
    var begin = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      end = moment().format("YYYY-MM-DD HH:mm:ss");
  }
  const params = {
    page: currentPage.value,
    size: pageSize.value,
    keywords: keywords.value,
    userId,
    begin,
    end,
    ...apiParams.value,
  };
  loading.value = true;
  mAxios.get(`bookmarks/list`, { params }).then((res) => {
    loading.value = false;
    res.data.data.rows.forEach((item) => {
      item.isChecked = false;
    });
    bookmarksList.value = res.data.data.rows;
    total.value = res.data.data.total;
    selectData.value = [];
  });
};
onMounted(() => {
  getBookMarksList();
});
watch(
  () => apiParams.value,
  (value) => {
    getBookMarksList();
  },
  {
    deep: true,
  }
);
// 翻页
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getBookMarksList();
};
const isIndeterminate = ref(false);
const selectData = ref([]);
const checkAll = ref(false);
const selectBookmark = () => {
  selectData.value = bookmarksList.value.filter((item) => item.isChecked);
  if (selectData.value.length == bookmarksList.value.length) {
    checkAll.value = true;
  } else {
    checkAll.value = false;
  }
};

const selectAllBookmarks = () => {
  if (checkAll.value) {
    bookmarksList.value.forEach((item) => {
      item.isChecked = true;
    });
  } else {
    bookmarksList.value.forEach((item) => {
      item.isChecked = false;
    });
  }
  selectBookmark();
};
const setAsterisks = (asterisk) => {
  let ids = selectData.value.map((item) => {
    return item.id;
  });
  mAxios.post("bookmarks/asterisk", { asterisk, ids }).then((res) => {
    res.data.succeed
      ? ElMessage.success("设置成功")
      : ElMessage.error("设置失败");
    getBookMarksList();
  });
};
const openPage = (url) => {
  window.open(url);
};
const bookmarkDetail = ref({});
const comments = ref([]);
const commentContent = ref("");
const likeCount = ref(0);
const likeStatus = ref(false);
const getComments = async () => {
  const { data: res } = await mAxios.get(
    `bookmarks/comment/${bookmarkDetail.value.id}`
  );
  comments.value = res.data || [];
};
const getLikeCount = async () => {
  const { data: res } = await mAxios.get(
    `bookmarks/like/${bookmarkDetail.value.id}`
  );
  if (res.data == 0 || res.data == null) {
    likeCount.value = "";
  } else {
    likeCount.value = res.data;
  }
};
const getLikeStatus = async () => {
  const params = {
    userId,
    bookmarkId: bookmarkDetail.value.id,
  };
  const { data: res } = await mAxios.post(`bookmarks/likeStatus`, params);
  likeStatus.value = res.data;
};
const viewPage = async (bookmark) => {
  bookmarkDetail.value = bookmark;
  dialog.isView = true;
  getLikeCount();
  getLikeStatus();
  getComments();
};
const commentSubmit = () => {
  const params = {
    userId,
    bookmarkId: bookmarkDetail.value.id,
    content: commentContent.value,
  };
  if (params.content == "") {
    ElMessage.error("评论内容不能为空");
    return;
  }
  mAxios.post("bookmarks/comment", params).then((res) => {
    commentContent.value = "";
    res.data.succeed
      ? ElMessage.success("评论成功")
      : ElMessage.error("评论失败");
    getComments();
  });
};
const delComment = (comment) => {
  mAxios
    .delete("bookmarks/comment", { data: { id: comment.id, userId } })
    .then((res) => {
      res.data.succeed
        ? ElMessage.success("删除成功")
        : ElMessage.error("删除失败");
      getComments();
    });
};
const handleLikeClick = () => {
  const params = {
    userId,
    bookmarkId: bookmarkDetail.value.id,
  };
  let req;
  if (likeStatus.value) {
    req = mAxios.delete("bookmarks/like", { data: params });
  } else {
    req = mAxios.post("bookmarks/like", params);
  }
  req.then((res) => {
    getLikeCount();
    getLikeStatus();
  });
};
const addBookMark = () => {
  isEdit.value = false;
  formData.value = {};
  formConfig.value = fields.slice(0, 2);
  dialog.visible = true;
};
const delBookMark = (id) => {
  let ids;
  if (id) {
    ids = [id];
  } else {
    ids = selectData.value.map((item) => {
      return item.id;
    });
  }
  console.log(ids);
  ElMessageBox.confirm("您确定要删除该书签？", "删除书签", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    center: true,
    closeOnClickModal: false,
    type: "warning",
  }).then(() => {
    mAxios.delete("bookmarks", { data: ids }).then((res) => {
      res.data.succeed
        ? ElMessage.success("删除成功")
        : ElMessage.error("删除失败");
      getBookMarksList();
    });
  });
};

const editBookMark = (id) => {
  formConfig.value = fields;
  mAxios.get("bookmarks/detail", { params: encodeURL({ id }) }).then((res) => {
    if (res.data.data) {
      res.data.data.tags = res.data.data.tags.filter((item) => item != 0);
    }
    formData.value = res.data.data || {};
    isEdit.value = true;
    dialog.visible = true;
  });
};
const setAsterisk = (item) => {
  const params = {
    ...item,
    asterisk: item.asterisk == 1 ? 0 : 1,
  };
  mAxios.put("bookmarks", params).then((res) => {
    res.data.succeed
      ? ElMessage.success("设置成功")
      : ElMessage.error("设置失败");
    getBookMarksList();
  });
};

const resetForm = () => {
  formData.value = {};
  formRef.value.resetFields();
};
defineExpose({ getBookMarksList });
</script>

<style scoped lang="scss">
:deep(.el-card__body) {
  padding: 0;
}
.empty {
  width: 100%;
  height: 80%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.bookmarks-box {
  width: 100%;
  padding: 20px;
  background-color: #fff;
  .head-operation-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }
  .toolbar {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    .el-checkbox {
      margin-right: 10px;
    }
  }
  .list-content {
    display: flex;
    flex-wrap: wrap;
    max-height: 700px;
    overflow: auto;
    .card-box {
      position: relative;
      width: 245px;
      margin: 0 15px 15px 0;
      cursor: pointer;
    }
  }
  .paginator-content {
    margin-top: 20px;
  }
}
.h-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
}
.card-body {
  padding: 5px;
  h1 {
    color: #191919;
    font-size: 0.93rem;
    font-weight: 500;
    width: auto;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    padding: 5px 0;
  }
  p {
    padding: 0;
    line-height: 22px;
    height: 47px;
    font-size: 0.85rem;
    overflow: hidden;
    color: #d1d1d2;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
  .b-f {
    height: 30px;
    color: #7f7c7e;
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    font-size: 13px;
    span {
      margin-left: 5px;
    }
  }
}
.iframe {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 99;
  background: #fff;
  .title {
    font-size: 16px;
    text-align: center;
    padding: 15px;
  }
  .close {
    position: absolute;
    top: 15px;
    right: 15px;
    cursor: pointer;
  }
  .tool {
    position: absolute;
    bottom: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 80px;
    box-shadow: 0px -1px 7px 1px #e0e0e0;
    background: #fff;
    z-index: 100;
    padding: 0 20px;
    ul {
      display: flex;
      li {
        display: flex;
        align-items: center;
        margin: 0 15px;
        cursor: pointer;
        color: #7f7c7e;
        img {
          width: 20px;
          height: 20px;
        }
      }
    }
  }
}
.drawer__content {
  width: 100%;
  height: 100%;
  overflow: auto;
  .comment_box {
    margin-bottom: 10px;
    .head {
      display: flex;
      position: relative;
      .avter {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 40px;
        height: 40px;
        background: #eee;
        border-radius: 50%;
        font-size: 22px;
        color: #bababa;
      }
      span {
        margin-right: 15px;
        font-size: 17px;
      }
      .username {
        padding-top: 4px;
        color: #727272;
      }
      .time {
        color: #7f7c7e;
        font-size: 14px;
        padding-top: 6px;
      }
      .icon {
        position: absolute;
        top: 5px;
        right: 5px;
        cursor: pointer;
      }
    }
    .body {
      width: 100%;
      min-height: 25px;
      max-height: 130px;
      padding-left: 55px;
      overflow: auto;
      color: #414141;
    }
  }
}
.drawer__footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  right: 0;
  box-shadow: 0px -1px 7px 1px #e0e0e0;
  background: #fff;
  padding: 20px;
  .foot_btn {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
}
</style>
